package com.itheima.reggie.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.utils.ThreadLocalUtil;
import com.itheima.reggie.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @Name : EmployeeInterceptor
 * @Author : WuQiang
 * @Date : 2022-08-10 11:23
 * @Description : 登录拦截器
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 校验登录状态，如果已经登录，则放行，未登录则拦截，返回未登录结果
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 处理器封装对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取本次请求的uri
        String requestURI = request.getRequestURI();
//        log.info("请求路径{}",requestURI);

        //2、判断session中是否有登录数据
        //后台登录
        Long empId = (Long) request.getSession().getAttribute("emp");
        if (empId != null) {
//            log.info("session存的empId:{}", empId);
            //存入ThreadLocal线程变量容器
            ThreadLocalUtil.setCurrentId(empId);
            //放行
            return true;
        }

        //前台登录
        Long userId = (Long) request.getSession().getAttribute("userId");
        if (userId != null) {
//            log.info("userId:{}", userId);
            //存入ThreadLocal线程变量容器
            ThreadLocalUtil.setCurrentId(userId);
            //放行
            return true;
        }
        //如果都为null
        if (userId == null || empId == null) {
            //没有登录
            new ObjectMapper().writeValue(response.getWriter(), R.error("NOTLOGIN"));
            //拦截
            return false;
        }
      return false;
    }
}
